package com.id.service.impl;

import com.id.service.OrderService;
import com.id.util.IdGeneratorSnowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author： yu.Tan
 * @Date: 2020/9/22 16:25
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private IdGeneratorSnowflake idGenerator;

    @Override
    public List<Long> getIDBySnowFlake() {
        List<Long> list=new ArrayList<>();

        /**
         * int corePoolSize, - 线程池核心池的大小。
         * int maximumPoolSize, - 线程池的最大线程数。
         * long keepAliveTime, - 当线程数大于核心时，此为终止前多余的空闲线程等待新任务的最长时间。
         * TimeUnit unit, - keepAliveTime 的时间单位。
         * BlockingQueue<Runnable> workQueue, - 用来储存等待执行任务的队列。
         * ThreadFactory threadFactory, - 线程工厂。
         * RejectedExecutionHandler handler)  - 拒绝策略。
         */
        ThreadPoolExecutor threadPool=
                new ThreadPoolExecutor(10,10,10, TimeUnit.SECONDS,
                        new ArrayBlockingQueue<Runnable>(1),
                        new ThreadPoolExecutor.DiscardOldestPolicy());

        threadPool.execute(()->{
            try{

                for (int i = 0; i < 20; i++) {
                    long id = idGenerator.snowflakeId();
                    System.out.println(id);
                    list.add(id);
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                threadPool.shutdown();
            }
        });

//        ExecutorService executorService = Executors.newFixedThreadPool(5);
//
//        for (int i = 0; i <= 20; i++) {
//            executorService.submit(()->{
//                long id = idGenerator.snowflakeId();
//                System.out.println(id);
//                list.add(id);
//            });
//        }
//        executorService.shutdown();
        return list;
    }
}
